<template>
  <a-form :form="loginForm">
    <a-form-item label="姓名" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <!-- 建议使用antd自带的v-decorator来定义表单项,建议封装校验方法，页面结构更清晰 -->
      <a-input v-decorator="['userName', rules.note]" />
    </a-form-item>
    <a-form-item label="年龄" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-input v-decorator="['age', rules.age]" type="number" />
    </a-form-item>
    <a-form-item label="手机号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-input v-decorator="['phone', rules.phone]" type="number" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
      <a-button type="primary" @click="handleSubmit">Submit</a-button>
      <a-button style="margin:0 20px;" type="primary" @click="setFormName">设置姓名为“安”</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
export default {
  name: 'FirstForm',
  data () {
    const maxAge = (rule, value, callback)=>{
      console.log({rule, value, callback})
      if(value < 0){
        callback('年龄不能小于0')
      }else if(value > 20){
        callback('年龄不能大于20')
      }else{
        callback()
      }

    }

    return {
      loginForm: this.$form.createForm(this, { name: 'FirstForm' }),  
      rules: {
        note: { rules: [
          { required: true, message: '请输入姓名!' },
          { max: 20,min: 1, message: '姓名介于1-20个字!' }
        ] },
        age: { 
          rules: [
            { required: true, message: '请输入年龄!' },
            {validator: maxAge}
          ],
          trigger: 'blur'
        },
        phone: {
          rules: [
            { required: true, message: '请输入正确的11位手机号!' ,len: 11}
          ],
          trigger: 'blur'
        }
      }
    }
  },
  methods: {
    handleSubmit (e) {
      //通过id获取值  ‘FirstForm_'+v-decorator的值
      const aa = document.getElementById('FirstForm_userName')

      console.log(aa)
      console.log(aa.value)
      
      //标准获取值
      this.loginForm.validateFields((err, values) => {
        if (!err) {
          console.log('form表单数据是: ', values)
        }
      })
      //另一种获取值的方法
      console.log(this.loginForm.getFieldsValue())
    },
    setFormName(){
      console.log('姓名为')
      this.loginForm.setFieldsValue({
        userName: '安',
        age: '20'
      })
    }
  }
}
</script>